// 路由鉴权 ：项目中路由能否被访问
import router from '@/router/index'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css' //必须引入样式才能显示
import useUserStore from './store/modules/user'
import pinia from './store/index'

let userStore = useUserStore(pinia)
let username = userStore.username
// 全局守卫：任意路由切换都会触发
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  let token = userStore.token
  if (token) {
    if (to.path == '/login') {
      next({ path: '/home' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 全局后置守卫
router.afterEach((to, from, next) => {
  document.title = '阳光优选-' + to.meta.title
  nprogress.done()
})
